﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
	public static partial class status
	{
		public static dynamic getStatusList(int start, int limit, string myusername, bool god,
			int? pid, string username, string school, int? lang, int? status)
		{
			var sql = new Sql.SqlDataContext();
			var ss = from s in sql.Status
					 where god || !s.god
					 select s;
			if (pid != null) ss = ss.Where(row => row.pid == pid);
			if (username != null) ss = ss.Where(row => row.username.ToLower() == username.ToLower());
			if (school != null) ss = from s in sql.Status
									 from u in sql.User
									 where u.username == s.username && u.school.Contains(school)
									 select s;
			if (lang != null) ss = ss.Where(row => row.lang == lang);
			if (status != null) ss = ss.Where(row => row.status == status);

			var total = ss.Count();
			var result = (from s in ss
						  from p in sql.Problem
						  from u in sql.User
						  from l in sql.Language
						  where p.pid == s.pid && u.username == s.username && l.code == s.lang
						  orderby s.rid descending
						  let allowCode = s.username == myusername
						  select new {
							  s.rid,
							  s.pid,
							  problemTitle = p.title,
							  s.username,
							  u.nickname,
							  submitTime = s.submitTime.toTimeString(),
							  lang = l.title,
							  langCode = s.lang,
							  codeLen = s.code.Length,
							  allowCode,
							  exeTime = god || s.status == 3 ? s.exeTime : null,
							  exeMem = god || s.status == 3  ? s.exeMem : null,
							  status = status2String(s.status),
							  statusCode = s.status,
							  reInfo = allowCode || god ? reCode2String(s.reCode) : null,
                              reCode = allowCode || god ? reCode2Hex(s.reCode) : null,
							  ceInfo = allowCode || god ? s.ceInfo : null,
							  s.god
						  }).Skip(start).Take(limit);
			return new {
				success = true,
				total,
				result
			};
		}
	}
}
